from captcha.image import ImageCaptcha
from io import BytesIO
import random
import string


def generate_captcha(width=None, height=None, fmt='JPEG'):
    characters = string.digits + string.ascii_lowercase
    if not width or not height:
        width, height, n_len, n_class = 200, 75, 4, len(characters)

    generator = ImageCaptcha(width=width, height=height)
    text = ''.join([random.choice(characters) for j in range(4)])
    image = generator.create_captcha_image(text, (0, 0, 153), (255, 255, 255))
    out = BytesIO()
    image.save(out, format=fmt)
    return text, out.getvalue()